﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Warehouse.DataAccess;
using System.Text;
using Warehouse.Web.AppCode;
using System.Configuration;
using System.Reflection;
using System.IO;

namespace Warehouse.Web.Management
{
    public partial class Authority : BasePage
    {
        StringBuilder panelTreeString = new StringBuilder();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //BindTree();
                BindPanelTree();
                BindPermissionTree();
            }
        }

        private void BindPanelTree()
        {
            Department[] departments = DataAccess.Department.GetDepartments();
            Department rootDep = departments.Where(item => item.ParentID == 0).SingleOrDefault();
            if (rootDep != null)
            {
                panelTreeString.Append("<ul id='depTree'>");

                panelTreeString.AppendFormat("<li><span class='icon-dep'></span><span class='li-treeitem' data-did='{1}'>{0}</span>", rootDep.Name, rootDep.ID);

                BindChildNode(rootDep, departments);

                panelTreeString.Append("</li>");

                panelTreeString.Append("</ul>");
            }
            panelTree.GroupingText = panelTreeString.ToString();
        }

        private void BindChildNode(Department parentDep, Department[] allDepartments)
        {
            var childDeps = allDepartments.Where(dep => dep.ParentID == parentDep.ID).ToArray();
            panelTreeString.Append("<ul>");
            if (childDeps.Length > 0)
            {
                foreach (Department childDep in childDeps)
                {
                    panelTreeString.AppendFormat("<li><span class='icon-dep'></span><span class='li-treeitem' data-did='{1}'>{0}</span>", childDep.Name, childDep.ID);

                    BindChildNode(childDep, allDepartments);

                    panelTreeString.Append("</li>");
                }
            }
            var users = DataAccess.User.GetUsersByDepID(parentDep.ID);
            if (users.Length > 0)
            {
                //panelTreeString.Append("<ul>");
                foreach (User user in users)
                {
                    panelTreeString.AppendFormat("<li class='userli' data-uid='{1}'>{0}</li>", user.Name, user.ID);
                }
                //panelTreeString.Append("</ul>");
            }
            panelTreeString.Append("</ul>");
        }

        protected override void ProcessAjaxRequest(HttpContext context, string action)
        {
            switch (action)
            {
                case "AddDepartment":
                    Department dep = new Department();
                    dep.Name = context.Request.Form["DepartmentName"];
                    try
                    {
                        dep.ParentID = int.Parse(context.Request.Form["ParentID"]);
                    }
                    catch (Exception e)
                    {
                        WebUtil.WriteJsonError(context, "上级部门ID必须是数字");
                        break;
                    }
                    Department parentDep = Department.GetDepartment(dep.ParentID);
                    if (parentDep != null)
                    {
                        dep.Save();
                        WebUtil.WriteJsonResult(context, new { DepartmentID = dep.ID });
                    }
                    else
                    {
                        WebUtil.WriteJsonError(context, "上级部门已经被删除");
                    }
                    break;
                case "EditDepartment":
                    int id = -1;
                    try
                    {
                        id = int.Parse(context.Request.Form["ID"]);
                    }
                    catch (Exception e)
                    {
                        WebUtil.WriteJsonError(context, "上级部门ID必须是数字");
                        break;
                    }
                    Department department = Department.GetDepartment(id);
                    if (department != null)
                    {
                        department.Name = context.Request.Form["DepartmentName"];
                        department.Save();
                        WebUtil.WriteJsonResult(context, null);
                    }
                    else
                    {
                        WebUtil.WriteJsonError(context, "该部门已经被删除");
                    }
                    break;
                case "DelDepartment":
                    Department delDep = Department.GetDepartment(int.Parse(context.Request.Form["ID"]));
                    if (delDep == null)
                    {
                        WebUtil.WriteJsonError(context, "该部门已经被删除,请刷新页面");
                        break;
                    }
                    if (delDep.ParentID == 0)
                    {
                        WebUtil.WriteJsonError(context, "不能删除根节点");
                        break;
                    }
                    delDep.Delete();
                    WebUtil.WriteJsonResult(context, null);
                    break;
                case "DelUser":
                    User delUser = new User();
                    delUser.ID = int.Parse(context.Request.Form["ID"]);
                    delUser.Delete();
                    WebUtil.WriteJsonResult(context, null);
                    break;
                case "AddUser":
                    User addUser = new User();
                    addUser.Name = context.Request.Form["Name"];
                    addUser.Gender = bool.Parse(context.Request.Form["Gender"]);
                    addUser.Telephone = context.Request.Form["Telephone"];
                    addUser.MobilePhone = context.Request.Form["MobilePhone"];
                    addUser.Password = context.Request.Form["Password"];
                    addUser.LoginName = context.Request.Form["LoginName"];
                    addUser.DepartmentID = int.Parse(context.Request.Form["DepartmentID"]);
                    addUser.Save();
                    WebUtil.WriteJsonResult(context, new { UserID = addUser.ID });
                    break;
                case "EditUser":
                    User editUser = DataAccess.User.GetUser(int.Parse(context.Request.Form["ID"]));
                    if (editUser != null)
                    {
                        editUser.Name = context.Request.Form["Name"];
                        editUser.Gender = bool.Parse(context.Request.Form["Gender"]);
                        editUser.Telephone = context.Request.Form["Telephone"];
                        editUser.MobilePhone = context.Request.Form["MobilePhone"];
                        editUser.Password = DataAccess.User.Encrypt(context.Request.Form["Password"]);
                        editUser.LoginName = context.Request.Form["LoginName"];
                        editUser.Save();
                        WebUtil.WriteJsonResult(context, null);
                    }
                    else
                    {
                        WebUtil.WriteJsonError(context, "该用户已被删除");
                    }
                    break;
                case "GetUser":
                    User user = DataAccess.User.GetUser(int.Parse(context.Request.QueryString["ID"]));
                    if (user != null)
                    {
                        WebUtil.WriteJsonResult(context, user);
                    }
                    else
                    {
                        WebUtil.WriteJsonError(context, "该用户已被删除");
                    }
                    break;
                case "GetPermissions":
                    DataAccess.PermissionInUser[] permissins = null;
                    if (context.Request.QueryString["Type"] == "d")
                    {
                        permissins = DataAccess.PermissionInUser.GetPermissionsByDep(int.Parse(context.Request.QueryString["ID"]));
                    }
                    else
                    {
                        permissins = DataAccess.PermissionInUser.GetPermissionsByUser(int.Parse(context.Request.QueryString["ID"]));
                    }
                    WebUtil.WriteJsonResult(context, permissins);
                    break;
                case "SavePermission":
                    DataAccess.PermissionInUser.SavePermission(int.Parse(context.Request.Form["TargetID"]), context.Request.Form["TargetType"], context.Request.Form["Permissions"]);
                    WebUtil.WriteJsonResult(context, null);
                    break;
            }
        }

        private void BindPermissionTree()
        {
            StringBuilder moduleTreeString = new StringBuilder();
            DataAccess.Module[] allModules = Warehouse.DataAccess.Module.GetModules();
            DataAccess.Permission[] allPermissions = DataAccess.Permission.GetPermissions();
            DataAccess.Module[] rootModules = allModules.Where(item => item.ParentID == 0).ToArray();

            if (rootModules.Length > 0)
            {
                moduleTreeString.Append("<ul>");
                foreach (DataAccess.Module module in rootModules)
                {
                    BindPermissionChildTree(module, allModules, allPermissions, moduleTreeString);
                }
                moduleTreeString.Append("</ul>");
            }
            permissionPanel.GroupingText = moduleTreeString.ToString();
        }

        private void BindPermissionChildTree(DataAccess.Module module, DataAccess.Module[] allModules, DataAccess.Permission[] allPermissions, StringBuilder moduleTreeString)
        {
            moduleTreeString.AppendFormat("<li><span class='pmtitle'>{0}</span>", module.Name);
            DataAccess.Permission[] permissions = allPermissions.Where(item => item.ModuleID == module.ID).OrderBy(item => item.ActionName).ToArray();
            if (permissions.Length > 0)
            {
                foreach (Permission permission in permissions)
                {
                    moduleTreeString.AppendFormat("<input type='checkbox' id='p_{0}'/>  {1} &nbsp;&nbsp;", permission.ID, permission.ActionName);
                }
            }

            DataAccess.Module[] childModules = allModules.Where(item => item.ParentID == module.ID).ToArray();
            if (childModules.Length > 0)
            {
                moduleTreeString.Append("<ul>");
                foreach (DataAccess.Module childModule in childModules)
                {
                    BindPermissionChildTree(childModule, allModules, allPermissions, moduleTreeString);
                }
                moduleTreeString.Append("</ul>");
            }

            moduleTreeString.Append("</li>");
        }

        /*
        private void BindTree()
        {
            Department[] departments = DataAccess.Department.GetDepartments();
            Department[] rootDeps = departments.Where(item => item.ParentID == 0).ToArray();
            if (rootDeps.Length > 0)
            {
                foreach (Department rootDep in rootDeps)
                {
                    TreeNode depNode = new TreeNode();
                    depNode.Text = rootDep.Name;
                    depNode.Value = rootDep.ID.ToString();
                    depNode.NavigateUrl = "javascript:alert(1);";

                    BindChildNode(depNode, departments);

                    depTree.Nodes.Add(depNode);
                }
            }
        }
        private void BindChildNode(TreeNode parentNode,Department[] allDepartments)
        {
            int depID = int.Parse(parentNode.Value);
            var childDeps = allDepartments.Where(dep => dep.ParentID == depID).ToList();
            if (childDeps != null)
            {
                foreach (Department childDep in childDeps)
                {
                    TreeNode depNode = new TreeNode();
                    depNode.Text = childDep.Name;
                    depNode.Value = childDep.ID.ToString();

                    BindChildNode(depNode, allDepartments);

                    parentNode.ChildNodes.Add(depNode);
                }
            }
            var users = DataAccess.User.GetUsersByDepID(depID);
            if (users.Length > 0)
            {
                foreach (User user in users)
                {
                    TreeNode userNode = new TreeNode();
                    userNode.Text = user.Name;
                    userNode.Value = user.ID.ToString();
                    parentNode.ChildNodes.Add(userNode);
                }
            }
        }
         */
    }
}